package com.t.bricks.bussiness.util.orders;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;

/**
 * 快递鸟查询快递工具类
 * @author HuangXinBian
 */
public class DelveryUtil {
	
	/**
	 * 请求url, 正式环境地址
	 */
	private static String reqURL = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";

	/**
	 * 即时查询接口 
	 * @param eBusinessID 快递鸟用户ID
	 * @param apiKey 快递鸟API key
	 * @param iRequestType 快递鸟API即时查询接口指令, 免费:1002;在途:8001;地图版:8003
	 * @param shipperCode 快递服务商编码
	 * @param logisticCode 订单编号
	 * @param sCustomerPhone 客户电话
	 * @return
	 */
	public static MsgEmity orderOnlineByJson(String eBusinessID, String apiKey,
			Integer iRequestType, String shipperCode, String logisticCode,
			String sCustomerPhone) {
		if (null == shipperCode || "".equals(shipperCode.trim()) || "null".equals(shipperCode.trim())) {
			return MsgEmity.err(1001, "服务商编码参数shipperCode不能为空");
		}

		if (null == logisticCode || "".equals(logisticCode.trim()) || "null".equals(logisticCode.trim())) {
			return MsgEmity.err(1002, "订单编号参数logisticCode不能为空");
		}
		
		if ("SF".equalsIgnoreCase(shipperCode)) {//查询顺丰，需要添加一个应用级参数CustomerName，String类型。其他快递查询请求暂不需要有此操作,CustomerName赋值寄件人或收件人的手机号后四位数字
			sCustomerPhone = sCustomerPhone.substring(sCustomerPhone.length() - 4);
		} else {
			sCustomerPhone = "";
		}
		
		// 组装应用级参数
		String RequestData = String.format("{'CustomerName':'%s','OrderCode': '','ShipperCode': '%s','LogisticCode': '%s',}", sCustomerPhone, shipperCode, logisticCode);
		
		String sRequestData = null;
		try {
			sRequestData = URLEncoder.encode(RequestData, "UTF-8");
		} catch (Exception e) {
			Log.error("转换数据发生异常:", e.getMessage());
			return MsgEmity.err(1003, "转换数据发生异常");
		}
		
		String dataSign = null;//电商Sign签名生成
		try {
			dataSign = MD5(RequestData + apiKey, "UTF-8");
			dataSign = Base64.encode(dataSign.getBytes("UTF-8"));
			dataSign = URLEncoder.encode(dataSign, "UTF-8");
		} catch (Exception e) {
			Log.error("转换数据发生异常:", e.getMessage());
			return MsgEmity.err(1004, "转换数据发生异常");
		}
		
		// 组装系统级参数
		Map<String,String> params = new HashMap<String,String>();
		params.put("RequestData", sRequestData);
		params.put("EBusinessID", eBusinessID);
		params.put("RequestType", iRequestType == null ? "1002" : iRequestType.toString());//免费即时查询接口指令1002/在途监控即时查询接口指令8001/地图版即时查询接口指令8003
		params.put("DataSign", dataSign);
		params.put("DataType", "2");
		// 以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数
		MsgEmity me = sendPost(reqURL, params);
		
		if (!me.isSuccess()) {
			return me.appendDataCode(100);
		}

		return me;//根据公司业务处理返回的信息......
	}

	/**
	 * MD5加密
	 * str 内容
	 * charset 编码方式
	 */
	private static String MD5(String str, String charset) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes(charset));
			byte[] result = md.digest();
			StringBuffer sb = new StringBuffer(32);
			for (int i = 0; i <result.length; i++) {
				int val = result[i] & 0xff;
				if (val <= 0xf) {
					sb.append("0");
				}
				sb.append(Integer.toHexString(val));
			}
			
			return sb.toString().toLowerCase();
		} catch (Exception e) {
			Log.error("MD5编码异常:", e.getMessage());
			return null;
		}
	}
	
	/**
	 * 向指定 URL 发送POST方法的请求
	 * url 发送请求的 URL
	 * params 请求的参数集合
	 * @return 远程资源的响应结果
	 */
	private static MsgEmity sendPost(String url, Map<String,String> params) {
		OutputStreamWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new	StringBuilder();
		
		try {
			URL realUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// POST方法
			conn.setRequestMethod("POST");
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.connect();
			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			
			// 发送请求参数
			if (params != null) {
				StringBuilder param = new	StringBuilder();
				for (Map.Entry<String,	String> entry : params.entrySet()) {
					if(param.length()>0){
						param.append("&");
					}
					param.append(entry.getKey());
					param.append("=");
					param.append(entry.getValue());
					System.out.println(entry.getKey()+":"+entry.getValue());
				}
				System.out.println("param:"+param.toString());
				out.write(param.toString());
			}
			
			// flush输出流的缓冲
			out.flush();
			
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
			Log.error("请求url发生异常:", e.getMessage());
			return MsgEmity.err(1001, "请求url发生异常:");
		} finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			} catch(IOException e){
				Log.error("关闭流发生异常:", e.getMessage());
			}
		}
		
		return new MsgEmity(true, "请求快递信息结束", result.toString());
	}
	
}
